Page({
  /**
   * 页面的初始数据
   */
  data: {
    messageInput: '',
    messages: [],

    BASE_URL: "127.0.0.1:8080/chat",
    SERVER_EMAIL: "88573134@qq.com",
    websocket: null,
    uuid: null,
    fromName: null,
    ip: null,
    serverUUID: "888888888888888888888",
    serverName: "客服",
    userInfo: {}
  },
  onShow() {
    this.setData({
      uuid: wx.getStorageSync('userInfo').userId
    })
    this.connectServer();
  },
  connectServer() {
    const that = this;
    wx.setStorageSync('CHAT_USER_UUID', this.data.uuid);
    wx.setStorageSync('CHAT_USER_FROMNAME', wx.getStorageSync('userInfo').username);
    wx.setStorageSync('CHAT_USER_IP', "");
    that.conectWebSocket();
  },
  conectWebSocket() {
    const that = this;
    if (wx.connectSocket) {
      wx.connectSocket({
        url: `ws://${that.data.BASE_URL}?token=${wx.getStorageSync('userInfo').token}`
      });
      wx.onSocketOpen(() => {
        console.log("连接成功");
      });
      wx.onSocketMessage((event) => {
        const notefi = JSON.parse(event.data);
        console.log("notefi", notefi);
        if (notefi.msgType === 0) {
          that.renderActive(notefi.userInfo);
        }
        if (notefi.msgType === 1) {
          that.renderNewMsg(notefi.allUUID);
        }
        if (notefi.msgType === 2) {
          const leaveUUID = notefi.leaveUUID;
          // 变灰
          that.updateUserStatus(leaveUUID, false);
        }
        if (notefi.msgType === 4) {
          that.sendEmail();
          that.renderNewMsg(notefi.allUUID);
        }
      });
      wx.onSocketError(() => {
        console.log("连接错误");
      });
      wx.onSocketClose(() => {
        console.log("连接关闭");
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '当前浏览器不支持 WebSocket'
      });
    }
  },
  sendEmail() {
    wx.request({
      url: `http://${this.data.BASE_URL}sendEmail`,
      data: { email: this.data.SERVER_EMAIL },
      success(res) {
        console.log(res);
      }
    });
  },
  renderNewMsg(allUUIDArray) {
    console.log("renderNewMsg", allUUIDArray)
    const chatRecords = allUUIDArray[0].chatRecords;
    // const boxEle = this.selectComponent(`#message-${this.data.serverUUID}`);
    const xcls = chatRecords[0].sendType === 0 ? 'xb' : 'xa';
    const self = chatRecords[0].sendType === 0 ? true : false;
    const odate = new Date();
    const msg = {
      class: xcls,
      self: self,
      content: chatRecords[0].msg,
      time: odate.toLocaleString('en-US', {
        hour: 'numeric',
        minute: 'numeric',
        hour12: true
      })
    };
    var _message = this.data.messages;
    _message.push(msg)
    this.setData({
      messages: _message
    })
    // boxEle.addMessage(msg);
  },
  renderActive(userInfo) {
    const chatRecords = userInfo.chatRecords;
    const isAlive = userInfo.serverAlive;
    const oneUUID = this.data.serverUUID;
    const oneNickname = this.data.serverName;
    const oneIP = '127.0.0.1';
    this.data.userInfo = {
      uuid: oneUUID,
      nickname: oneNickname,
      ip: oneIP
    };
    if (isAlive === 0) {
      this.updateUserStatus(oneUUID, false);
    }
    var _messages = [];
    // const boxEle = this.selectComponent(`#message-${oneUUID}`);
    chatRecords.forEach(record => {
      const xcls = record.sendType === 0 ? 'xb' : 'xa';
      const self = record.sendType === 0 ? true : false;
      const odate = new Date();
      const msg = {
        class: xcls,
        self: self,
        content: record.msg,
        time: odate.toLocaleString('en-US', {
          hour: 'numeric',
          minute: 'numeric',
          hour12: true
        })
      };
      _messages.push(msg)
      // boxEle.addMessage(msg);
    });
    console.log("_messages", _messages)
    this.setData({
      messages: _messages
    })
  },
  updateUserStatus(uuid, isOnline) {
    const userEle = this.selectComponent(`b[uuid^='${uuid}']`);
    if (userEle) {
      userEle.setData({
        class: isOnline ? '' : 'outline-user'
      });
    }
  },
  send() {
    var message = this.data.messageInput;
    const msgTime = this.dateTime2str(new Date(), "yyyy-MM-dd hh:mm:ss");
    const socketMsg = {
      msg: message,
      toUser: this.data.serverUUID,
      toName: this.data.serverName,
      fromUser: this.data.uuid,
      fromName: this.data.fromName,
      msgTime: msgTime,
      sendType: 0,
      ip: this.data.ip,
      msgType: 1,
      type: 1
    };
    wx.sendSocketMessage({
      data: JSON.stringify(socketMsg)
    });
    this.setData({
      messageInput: ""
    })
  },
  dateTime2str(dateTime, format) {
    const z = {
      y: dateTime.getFullYear(),
      M: dateTime.getMonth() + 1,
      d: dateTime.getDate(),
      h: dateTime.getHours(),
      m: dateTime.getMinutes(),
      s: dateTime.getSeconds()
    };
    return format.replace(/(y+|M+|d+|h+|m+|s+)/g, v => {
      return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2);
    });
  }
})